<template> 
  <div class="map-page">
    <div class="header">
      <button @click="goBack" class="back-button">返回</button>
      <span class="title">地图寻宝</span>
    </div>
    
    <div class="map-container">
      <div class="map-box">
        <div id="map" ref="mapContainer"></div>
        
        <!-- 自定义选择控件 -->
        <div class="fab-container">
          <button 
            :class="['fab-button', { active: selectedType === 'museums' }]" 
            @click="changeType('museums')"
            title="博物馆"
          >
            <i class="fas fa-landmark"></i>
          </button>
          <button 
            :class="['fab-button', { active: selectedType === 'bronze_sites' }]" 
            @click="changeType('bronze_sites')"
            title="古青铜遗址"
          >
            <i class="fas fa-archway"></i>
          </button>
        </div>
        
        <!-- 当前定位按钮 -->
        <div class="locate-container">
          <button 
            @click="locateUser" 
            :class="['locate-button', { locating: isLocating }]" 
            title="显示当前位置"
          >
            <i class="fas fa-map-marker-alt"></i>
          </button>
        </div>
        
        <!-- 信息框 -->
        <transition name="fade">
          <div v-if="selectedItem" class="info-box">
            <button class="close-button" @click="closeInfoBox">×</button>
            <div class="info-content">
              <h3>{{ selectedItem.name }}</h3>
              <p>{{ selectedItem.description }}</p>
              <p>地址：{{ selectedItem.location }}</p>
              <p v-if="selectedType === 'museums'">成立时间：{{ selectedItem.established_time }}</p>
              <img :src="selectedItem.image_url" :alt="selectedItem.name" />
            </div>
          </div>
        </transition>
        
        <!-- 地图来源和审图号标注
        <div class="map-credits">
          地图数据 &copy; <a href="https://www.amap.com/" target="_blank">高德地图</a>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from 'axios';
import '@fortawesome/fontawesome-free/css/all.css';
import { BASE_URL } from '@/config.js';
export default {
  name: 'MapView',
  data() {
    return {
      map: null,
      items: [], // 存储当前选中的数据（博物馆或遗址）
      selectedItem: null, // 当前选中的项目
      selectedType: 'museums', // 当前选择的数据类型：'museums' 或 'bronze_sites'
      markers: [], // 存储当前的标记
      isLocating: false, // 是否正在定位
      userMarker: null, // 用户位置标记
      fromSection: null,
      markerIcons: {
        museums: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png',
        bronze_sites: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        user: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
      }
    };
  },
  mounted() {
    this.initMap();
    this.fromSection = this.$route.query.fromSection;
  },
  methods: {
    goBack() {
      if (this.fromSection !== null) {
        this.$router.push({ name: 'Home', query: { scrollToSection: this.fromSection } });
      } else {
        this.$router.push({ name: 'Home' });
      }
    },
    changeType(type) {
      if (this.selectedType !== type) {
        this.selectedType = type;
        this.fetchData();
      }
    },
    async initMap() {
      // 设置安全密钥
      window._AMapSecurityConfig = {
        securityJsCode: "c96c05dc0050b99b6b6c8dc5b68fdea9", // 替换为您的安全密钥
      };
      
      try {
        const AMap = await AMapLoader.load({
          key: "26c2b1e8b62188debbe91642692ef043", // 替换为您的高德地图API密钥
          version: "2.0",
          plugins: [], // 不加载额外的插件
        });

        // 初始化地图
        this.map = new AMap.Map(this.$refs.mapContainer, {
          zoom: 4,
          center: [104.1954, 35.8617], // 中国的中心坐标
          viewMode: "2D", // 使用二维地图模式
          mapStyle: "amap://styles/normal", // 使用标准地图样式
          resizeEnable: true,
        });

        // 限制地图的可视范围
        const southWest = new AMap.LngLat(73.4994 - 10, 3.0);
        const northEast = new AMap.LngLat(134.7728 + 10, 53.5609 + 5);
        const mapBounds = new AMap.Bounds(southWest, northEast);
        this.map.setLimitBounds(mapBounds);

        // 地图初始化完成后加载标记点
        this.fetchData();

      } catch (error) {
        console.error('加载高德地图失败:', error);
      }
    },
    async fetchData() {
      try {
        let response;
        if (this.selectedType === 'museums') {
          response = await axios.get('/api/museums');
        } else if (this.selectedType === 'bronze_sites') {
          response = await axios.get('/api/bronze_sites');
        }
        this.items = response.data;
        console.log('Fetched items:', this.items); // 调试日志
        this.addMarkers();
      } catch (error) {
        console.error(`Error fetching ${this.selectedType}:`, error);
      }
    },
    closeInfoBox() {
      this.selectedItem = null;
    },
    addMarkers() {
      if (!this.map) {
        console.error('地图未初始化');
        return;
      }

      // 清除现有的标记
      this.markers.forEach(marker => marker.setMap(null));
      this.markers = [];

      this.items.forEach((item) => {
        // 创建标记
        const marker = new AMap.Marker({
          position: [item.longitude, item.latitude],
          icon: this.markerIcons[this.selectedType],
          map: this.map,
        });

        // 添加点击事件
        marker.on('click', () => {
          this.selectedItem = item;
          this.map.setCenter(marker.getPosition());
        });

        // 添加鼠标悬停事件以改变光标
        marker.on('mouseover', () => {
          this.map.setDefaultCursor('pointer');
        });
        marker.on('mouseout', () => {
          this.map.setDefaultCursor('');
        });

        this.markers.push(marker);
        console.log('Added marker:', item); // 调试日志
      });
    },
    locateUser() {
      if (!navigator.geolocation) {
        alert('您的浏览器不支持地理定位');
        return;
      }

      this.isLocating = true;

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
          const userLatLng = new AMap.LngLat(longitude, latitude);

          // 移除之前的用户标记
          if (this.userMarker) {
            this.userMarker.setMap(null);
          }

          // 创建用户位置标记
          this.userMarker = new AMap.Marker({
            position: userLatLng,
            icon: this.markerIcons['user'],
            map: this.map,
          });

          const infoWindow = new AMap.InfoWindow({
            content: '您当前的位置',
            offset: new AMap.Pixel(0, -30),
          });
          infoWindow.open(this.map, userLatLng);

          this.map.setCenter(userLatLng);
          this.map.setZoom(14);
          this.isLocating = false;
        },
        (error) => {
          console.error('定位失败:', error);
          alert('无法获取您的位置信息');
          this.isLocating = false;
        }
      );
    },
  },
};
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');

.map-page {
  margin-top: 52px;
  flex-direction: column;
  align-items: center;
  font-family: 'Roboto', sans-serif;
  height: 100vh;
  background: #000000;
  padding: 20px;

  /* 根据需要调整或移除背景图 */
  /* background-image: url('@/assets/background_9.jpg'); */
  background-repeat: no-repeat; /* 背景图不重复 */
  background-size: cover; /* 背景图覆盖整个区域 */
  background-position: center; /* 背景图居中 */
  background-attachment: fixed; /* 背景图固定 */
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  background: linear-gradient(45deg, #5e4b3c, #8b4513); /* 深棕色到青铜色的渐变 */
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0,0,0,0.5);
  position: relative; /* 保持返回按钮在头部 */
}

.back-button {
  position: absolute;
  left: 20px;
  background-color: #8b4513; /* 深棕色 */
  color: #fdf6e3;
  border: none;
  padding: 12px 24px;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  border-radius: 25px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(0,0,0,0.3);
}

.back-button:hover {
  background-color: #5e4b3c; /* 更深的棕色 */
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0,0,0,0.5);
}

.title {
  font-size: 26px;
  font-weight: 700;
  font-family: 'SimSun', 'STSong', serif;
  color: #fdf6e3; /* 淡色字体 */
}

.map-container {
  width: 80%;
  max-width: 1400px;
  height: 80vh;
  margin-left: 10vw;
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.map-box {
  width: 100%;
  height: 100%;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
}

.fab-container {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  z-index: 1000;
}

.fab-button {
  width: 50px;
  height: 50px;
  background-color: rgba(44, 62, 80, 0.8);
  color: #ecf0f1;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
}

.fab-button:hover {
  background-color: #34495e;
  transform: scale(1.1);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.fab-button.active {
  background-color: #3498db;
  box-shadow: 0 6px 12px rgba(52, 152, 219, 0.4);
}

.locate-container {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.locate-button {
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #6dd5ed, #2193b0);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s, box-shadow 0.3s, background 0.3s;
}

.locate-button:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.locate-button.locating {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(33, 147, 176, 0.4);
  }
  70% {
    box-shadow: 0 0 0 20px rgba(33, 147, 176, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(33, 147, 176, 0);
  }
}

.info-box {
  position: absolute;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  width: 350px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  z-index: 1000;
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translate(-50%, 50px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}

.info-content {
  overflow-y: auto;
  max-height: 300px;
  padding-top: 10px;
}

.info-content h3 {
  font-weight: 700;
  color: #2980b9;
  margin-bottom: 0.5em;
}

.info-content p {
  margin-bottom: 1em;
  color: #2c3e50;
  line-height: 1.5;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background: transparent;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #7f8c8d;
  transition: color 0.3s;
}

.close-button:hover {
  color: #e74c3c;
}

.info-content img {
  width: 100%;
  height: auto;
  border-radius: 8px;
  margin-top: 10px;
  transition: transform 0.3s;
}

.info-content img:hover {
  transform: scale(1.02);
}

/* 地图来源和审图号标注样式 */
.map-credits {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px;
  color: #2c3e50;
  z-index: 1000;
}

.map-credits a {
  color: #2980b9;
  text-decoration: none;
}

.map-credits a:hover {
  text-decoration: underline;
}

/* 动画过渡 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active for <2.1.8 */ {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .title {
    font-size: 20px;
  }

  .back-button {
    padding: 8px 14px;
    font-size: 12px;
  }

  .fab-button {
    width: 45px;
    height: 45px;
    font-size: 18px;
  }

  .info-box {
    width: 90%;
    bottom: 20px;
  }

  .map-credits {
    font-size: 10px;
    padding: 3px 6px;
  }
}
</style>
